<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams">
      <el-form-item label="名称" prop="fmName">
        <el-input
          v-model="queryParams.fmName"
          clearable
          placeholder="请输入名称"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件后缀" prop="fileExt">
        <el-input
          v-model="queryParams.fileExt"
          clearable
          placeholder="请输入文件后缀"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="cyan" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-upload
          :action="uploadOpt.action"
          :auto-upload="true"
          :data="uploadOpt.data"
          :headers="uploadOpt.headers"
          :limit="1"
          :on-error="fileUploadError"
          :on-success="fileUploadSuccess"
          :show-file-list="false"
          class="upload-demo">
          <el-button icon="el-icon-upload" size="mini" type="success">上传</el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button-group>
          <el-button
            v-hasPermi="['fm:node:add']"
            icon="el-icon-plus"
            size="mini"
            type="primary"
            @click="addRow"
          >新增文件夹
          </el-button>
          <el-button
            v-hasPermi="['fm:node:edit']"
            :disabled="single"
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="changeEditing"
          >重命名
          </el-button>
          <el-button
            v-hasPermi="['fm:node:remove']"
            :disabled="single"
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="handleDelete"
          >删除
          </el-button>
        </el-button-group>
      </el-col>
      <el-col :span="1.5">
        <el-button-group>
          <el-button
            v-hasPermi="['fm:node:edit']"
            :disabled="single || selectRowIsEncrypt"
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="setPassword"
          >设置密码
          </el-button>
          <el-button
            v-hasPermi="['fm:node:edit']"
            :disabled="single || !selectRowIsEncrypt"
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="cancelPassword"
          >取消密码
          </el-button>
        </el-button-group>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="nodeList" height="calc(100vh - 201px)" highlight-current-row
              @current-change="handleCurrentChange">
      <el-table-column align="left" label="名称">
        <template slot-scope="scope">
          <div v-if="scope.row.id!==editingId">
            <i v-if="scope.row.fmType==='D'" class="el-icon-folder type-icon type-d-icon"></i>
            <i v-if="scope.row.fmType==='F'" class="el-icon-document type-icon type-f-icon"></i>
            <span class="fm-list-name" @click="fileNameClick(scope.row)">{{ scope.row.fmName }}</span>
            <i v-if="scope.row.isEncrypt==='Y'" class="el-icon-lock lock-icon"></i>
          </div>
          <div v-else>
            <el-input :ref="'fileNameInput'+scope.row.id" v-model="editingValue"
                      placeholder="请输入文件夹名称" @keyup.enter.native="updateFmName"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="文件大小" prop="fileSizeStr" width="100"/>
      <el-table-column align="center" label="创建者" prop="createBy" width="200"/>
      <el-table-column align="center" label="创建时间" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <div class="breadcrumb-container">
      <el-row>
        <el-col :span="20">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item v-for="(bd, bdIndex) in breadcrumbDataArr"><span @click="breadcrumbClick(bd, bdIndex)">{{ bd.text }}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </el-col>
        <el-col :span="4">
          <!--        <div class="back-parent" @click="backParent">-->
          <!--          <i class="el-icon-top"></i>-->
          <!--          <span>返回上一级</span>-->
          <!--        </div>-->
        </el-col>
      </el-row>
    </div>


  </div>
</template>

<script>
import {delNode, listNode} from '@/api/fm/node'
import {addNode, checkPassword, listNodeByParent, updateNode} from '../../../api/fm/node'
import {getToken} from '../../../utils/auth'
import md5 from 'js-md5'

export default {
  name: 'Node',
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      id: '',        // 选中数组
      selectedRow: '',
      // 当前页面的parentId
      parentId: undefined,
      // 编辑行对应的id
      editingId: -1,
      // 编辑行对应的value
      editingValue: '',
      // 非单个禁用
      single: true,
      // 选中行是否加密
      selectRowIsEncrypt: false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 文件管理表格数据
      nodeList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fmName: null,
        fileExt: null,
        isEncrypt: null
      },
      //上传参数
      uploadOpt: {
        action: process.env.VUE_APP_BASE_API + '/fm/node/upload',
        data: {
          parentId: this.parentId ? this.parentId : -1
        },
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()}
      },
      // 面包屑数组
      breadcrumbDataArr: [
        {
          id: undefined,
          text: '根目录',
          to: '/fm/node'
        }
      ]
    }

  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询文件管理列表 */
    getList(parentId) {
      if (parentId) {
        this.parentId = parentId
        this.loading = true
        listNodeByParent(parentId).then(response => {
          this.nodeList = response.rows
          this.total = response.total
          this.loading = false
        })
      } else {
        this.loading = true
        listNode(this.queryParams).then(response => {
          this.nodeList = response.rows
          this.total = response.total
          this.loading = false
        })
      }

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    //选中数据
    handleCurrentChange(val) {
      if (val) {
        this.id = val.id
        this.selectedRow = val
        if (this.id) {
          this.single = false
        }
        this.selectRowIsEncrypt = val.isEncrypt === 'Y'
      }
    },
    //点击文件名称
    fileNameClick(row) {
      if (row.isEncrypt === 'Y') {
        this.$prompt('请输入密码', '安全验证', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\w+/,
          inputErrorMessage: '密码不能为空，且只能是字母、数字组合',
          inputType: 'password'
        }).then(({value}) => {
          checkPassword(this.id, md5(value)).then(response => {
            if (response.code === 200) {
              this.msgSuccess('密码正确')

              this.goChildOrDownload(row)
            } else {
              this.msgError('密码设置失败，请重试')
            }
          })
        }).catch(() => {

        })
      } else {
        this.goChildOrDownload(row)
      }
    },
    /** 新增按钮操作 */
    addRow() {
      let node = {
        parentId: this.parentId,
        fmName: '新建文件夹',
        fmType: 'D',
        isEncrypt: 'N'
      }
      let t = this
      addNode(node).then(response => {
        if (response.code === 200) {
          this.getList(this.parentId)
          this.editingId = response.data.id
          t.$nextTick(() => {
            t.$refs['fileNameInput' + this.editingId].$refs.input.focus()
          })

        } else {
          this.msgError('新建文件夹失败，请稍后重试')
        }
      })

    },
    /** 删除按钮操作 */
    handleDelete() {
      const ids = this.id
      const fmName = this.selectedRow.fmName
      this.$confirm('是否确认删除文件名为"' + fmName + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delNode(ids)
      }).then(() => {
        this.getList(this.parentId)
        this.msgSuccess('删除成功')
      }).catch(function () {
      })
    },
    // 开始编辑文件夹名称
    changeEditing() {
      this.editingId = this.id
    },
    // 更新文件夹名称
    updateFmName() {
      let node = {
        id: this.editingId,
        fmName: this.editingValue
      }
      updateNode(node).then(response => {
        if (response.code === 200) {
          this.editingId = -1
          this.editingValue = ''

          // this.msgSuccess('重命名成功')
          this.getList(this.parentId)
        }
      })
    },
    //上传成功
    fileUploadSuccess() {
      this.getList(this.parentId)
    },
    //上传失败
    fileUploadError() {
      this.msgError('上传失败')
    },
    //设置密码
    setPassword() {
      this.$prompt('密码只能是字母、数字组合', '设置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\w+/,
        inputErrorMessage: '密码不能为空，且只能是字母、数字组合',
        inputType: 'password'
      }).then(({value}) => {
        updateNode({
          id: this.id,
          password: md5(value)
        }).then(response => {
          if (response.code === 200) {
            this.msgSuccess('密码设置成功')
            this.getList(this.parentId)
          } else {
            this.msgError('密码设置失败，请稍后重试')
          }
        })
      }).catch(() => {
      })
    },
    // 取消密码
    cancelPassword() {
      this.$confirm('确认取消密码?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(({value}) => {
        updateNode({
          id: this.id,
          password: ''
        }).then(response => {
          if (response.code === 200) {
            this.msgSuccess('取消密码成功')
            this.getList(this.parentId)
          } else {
            this.msgError('取消密码失败，请稍后重试')
          }
        })
      }).catch(() => {
      })
    },
    // 点击名称实际逻辑
    goChildOrDownload(row) {
      if (row.fmType === 'D') {
        this.getList(row.id)

        this.breadcrumbDataArr.push({
          id: row.id,
          text: row.fmName,
          to: '/fm/node/listByParent/' + row.id
        })
      } else {
        if (row.fileUrl) {
          window.open(process.env.VUE_APP_BASE_API + row.fileUrl)
        }
      }
    },
    // 面包屑 点击事件
    breadcrumbClick(clickedBreadcrumb, clickedIndex) {
      this.breadcrumbDataArr = this.breadcrumbDataArr.filter((item, index) => {
        return index <= clickedIndex
      })

      this.parentId = clickedBreadcrumb.id
      this.getList(this.parentId)
    }
  }
}
</script>
<style lang="scss" scoped>
.type-icon {
  font-size: 16px;
  margin-right: 5px;
}

.type-d-icon {
  color: #85B1CC
}

.type-f-icon {
  color: #A5A5A5;
}

.fm-list-name {
  cursor: pointer;
}

.lock-icon {
  font-size: 12px;
  margin-left: 2px;
  color: #F56C6C;
}

.breadcrumb-container {
  padding: 10px 0 10px 30px;
}

.back-parent {
  font-size: 14px;
  color: #000000;
  height: 14px;
  line-height: 14px;
}

.back-parent i {
  font-size: 16px;
}
</style>
<style lang="scss">
.el-breadcrumb__inner {
  cursor: pointer;
}
</style>
